<?php
/*
 * @Descripttion: 
 * @version: 1.0
 * @Author: Sam
 * date: 2021-09-22 10:06:31
 * @LastEditors: Sam
 * @LastEditTime: 2022-10-18 18:16:40
 */
namespace app\api\controller;
use app\__MODULE__\model\{Distributor as DistributorModel,UserCommission,Withdrawal,BalanceLog};
use hg\apidoc\annotation as Apidoc;


class Distributor extends ApiBase{


        /**
     * @Apidoc\Title("申请分销商")
     * @Apidoc\Url("/api/commission_apply")
     * @Apidoc\Desc("需要token验证")
     * @Apidoc\Method("post")
     * @Apidoc\param("reason", type="string", desc="理由")
     */
    public function commission_apply(){
        $reason = input('post.reason');
        $uid = $this->get_user_id();
        $user_info = $this->get_user_info();
        if($user_info['did'] > 0 &&  DistributorModel::where('uid',$uid)->where('status',1)->count() > 0){
            json_response(0,'您已经是分销商了');
        }
        if(DistributorModel::where('uid',$uid)->where('status',0)->field('id')->count()){
            json_response(0,'您已经申请过了,请等待审核');
        }
        if(empty($user_info['mobile']))  json_response(0,'请先授权手机号');
        $data = [
            'uid' => $uid,
            'reason' => $reason,
            'status' => 0,
            'nickname' => $user_info['nickname'],
            'mobile'   => $user_info['mobile'],
            'create_time' => time()
        ];
        $res = DistributorModel::create($data);
        if($res) {
            json_response(1,'申请成功');
        }else{
            json_response(1,'申请失败');
        }
    }


        /**
     * @Apidoc\Title("我的佣金")
     * @Apidoc\Url("/api/user_commission")
     * @Apidoc\Desc("需要token验证")
     * @Apidoc\Method("get")
     * @Apidoc\param("page", type="int", desc="页码")
     * @Apidoc\param("limit", type="int", desc="数量")
     * @Apidoc\param("date", type="string", desc="日期")
     * @Apidoc\Returned("[]", type="object", desc="佣金列表",
     *          @Apidoc\Returned("order_sn", type="string", desc="订单"),
     *          @Apidoc\Returned("user_commission", type="string", desc="佣金"),
     *          @Apidoc\Returned("order_pay_price", type="string", desc="订单金额"),
     *          @Apidoc\Returned("status", type="int", desc="-1 待入账 0 已入账 2已退款")
     * )
     * 
     */
    public function user_commission(){
        $user = $this->get_user_info();
        if(!$Distributor = DistributorModel::where('uid',$user['id'])->find()) json_response(0,'您不是分销员');
        if($Distributor->status == 0)  json_response(0,'您的申请还在审核中');
        $page  = request()->param('page/d',1);
        $limit = request()->param('limit/d',10);
        $date  = request()->param('date');
        $where = [];
        $where[] = ['uid','=',$user['id']];
        $where[] = ['status','=',0];
        if($date){
            $where[] = ['create_time','between time',[strtotime($date),strtotime($date.'23:59:59')]];
        }
        
        $user_commission = UserCommission::with(['order'])->where($where)->page($page,$limit)->field('id,oid,order_sn,status,user_commission,order_pay_price,create_time,nickname,avatar')->order('id desc')->hidden(['order'])->select();
        json_response(1,'success',$user_commission);
    }

    
       /**
     * @Apidoc\Title("提现申请")
     * @Apidoc\Url("/api/withdrawal")
     * @Apidoc\Desc("需要token验证")
     * @Apidoc\Method("post")
     * @Apidoc\param("amount", type="string", desc="提现金额")
     */
    public function withdrawal(){
        $user = $this->get_user_info();
        redis_lock("{$this->redis_key}:withdrawal:{$user['id']}",$user,function($user,$redis){
            if(!$user['did']) return error('当前用户并非分销员');
            $distru_user = DistributorModel::find($user['did']);
            if($distru_user->status == -1)  return error('当前分销员账号已被冻结');
            $amount     = request()->post('amount');
            if($amount <=0)   return error('金额不得为空');
            if($distru_user->balance < $amount)   return error('余额不足');
            $user_amount =  UserCommission::where(['uid'=>$user['id'],'status'=>0])->sum('user_commission');
            if($user_amount < $distru_user->balance)  return error('账号异常');
            Db::startTrans();
            try {
                if(Withdrawal::where(['uid'=>$user['id'],'status'=>0])->count())  return error('您有一笔提现审核中');
                Withdrawal::create([
                    'uid'      => $user['id'],
                    'did'      => $user['did'],
                    'amount'   => $amount
                ]);
               $res  =  DistributorModel::outcome($user['id'],$amount);
               if(!$res) return error('操作失败');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return error($e->getMessage().$e->getFile());
            }
            return success('提交成功');
        },3);
    }

               /**
     * @Apidoc\Title("分销员详情")
     * @Apidoc\Url("/api/user_distributor_detail")
     * @Apidoc\Desc("需要token验证")
     * @Apidoc\Method("get")
     * @Apidoc\Returned("distributor", type="object", desc="分销员详情",
     *          @Apidoc\Returned("nickname", type="strinig", desc="姓名"),
     *          @Apidoc\Returned("mobile", type="strinig", desc="手机号"),
     *          @Apidoc\Returned("level_name", type="strinig", desc="等级名称"),
     *          @Apidoc\Returned("balcance", type="strinig", desc="余额 可提现金额"),
     * ),
     * @Apidoc\Returned("all_commission", type="string", desc="累计佣金"),
     * @Apidoc\Returned("today_commission", type="string", desc="今日佣金"),
     * @Apidoc\Returned("commission_list", type="object", desc="佣金列表",
     *          @Apidoc\Returned("user_commission", type="strinig", desc="佣金"),
     *          @Apidoc\Returned("nickname", type="string", desc="昵称"),
     *          @Apidoc\Returned("avatar", type="string", desc="头像"),
     *          @Apidoc\Returned("order_pay_price", type="string", desc="订单金额"),
     *          @Apidoc\Returned("create_time", type="string", desc="时间")
     * ),
     */
    public function user_distributor_detail(){
        $user     = $this->get_user_info();
        if( empty($user['did'])) json_response(0,'当前用户不是分销员');
        $distributor = DistributorModel::where('id',$user['did'])->field('nickname,name,mobile,level,status,balance')->hidden(['levelInfo'])->find();
        if(empty($distributor)) json_response(0,'没找到分销员信息');
        if($distributor->status != 1) json_response(0,'当前分销员账号还在审核或被拒绝');
        $distributor['level_name'] = $distributor['levelInfo']['level_name'];
        // $distributor->rules = freshCache('distribution.rules') !=null ? freshCache('distribution.rules') : '';
        $all_commission     = UserCommission::where('uid',$user['id'])->where('status','in',[-1,0])->sum('user_commission') ?? 0;
        $today_commission   = UserCommission::where('uid',$user['id'])->where('status','in',[-1,0])->where('create_time','today')->sum('user_commission') ?? 0;
        $commission_list    = UserCommission::where('uid',$user['id'])->order('id desc')->limit(10)->field('id,user_commission,create_time,order_pay_price,nickname,avatar,total_num')->select();
        json_response(1,'success',compact('distributor','all_commission','today_commission','commission_list'));
    }

           /**
     * @Apidoc\Title("我的余额记录")
     * @Apidoc\Url("/api/balance_log")
     * @Apidoc\Desc("需要token验证")
     * @Apidoc\Method("get")
     * @Apidoc\param("", type="string", desc="提现金额")
     */
    public function balance_log(){
        $user     = $this->get_user_info();
        $dis_user = Distributor::get($user['did']);
        $page     = request()->param('page/d',1);
        $limit    = request()->param('limit/d',10);
        $all_balance = 0;
        $balance     = 0;
        $list        = [];
        if($dis_user){
           if($dis_user->status !=0) json_response(0,'状态异常');
           $balance = $dis_user->balance;
           $all_balance  = UserCommission::where('uid',$user['id'])->where('status','in',[-1,0])->sum('user_commission') ?? 0;
           $list         = BalanceLog::where('uid',$user['id'])->where('did',$dis_user->id)->where('source',1)->page($page,$limit)->field('amount,type,spec,create_time')->select();
        }
      
        json_response(1,'success',compact('balance','all_balance','list','withdraw_rule'));
    }
}